/*
 Copyright (c) 2012 Roman Truba

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial
 portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
 THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.edgclub.edg.uc.galleryviewpager;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.edgclub.edg.Constant;
import com.edgclub.edg.R;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.util.FileUtility;
import com.edgclub.edg.utils.util.StringUtils;

import java.io.File;

public class UrlTouchImageViewForImage extends RelativeLayout {
	protected TextView tvProgress;
	protected TouchImageView1 mImageView;
	protected ImageView mGifImageView;
	private String imageUrl;

	protected Context mContext;

	private GlideUtils imageLoaderClient;

	private BitmapFactory.Options opt;

	public UrlTouchImageViewForImage(Context ctx) {
		super(ctx);
		mContext = ctx;
		init();

	}

	public UrlTouchImageViewForImage(Context ctx, AttributeSet attrs) {
		super(ctx, attrs);
		mContext = ctx;
		init();
	}

	public TouchImageView1 getImageView() {
		return mImageView;
	}
	public String getImageUrl() {
		return imageUrl;
	}

	protected void init() {
		imageLoaderClient = new GlideUtils();
		opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		opt.inSampleSize = 50;
		mImageView = new TouchImageView1(mContext);
		mGifImageView = new ImageView(mContext);
		mGifImageView.setTag(mContext);
		setBackgroundColor(Color.BLACK);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		mImageView.setLayoutParams(params);
		mGifImageView.setLayoutParams(params);
		this.addView(mImageView);
		this.addView(mGifImageView);
		mImageView.setVisibility(GONE);
		mGifImageView.setVisibility(GONE);
		tvProgress = new TextView(mContext);
		tvProgress.setGravity(Gravity.CENTER);
		tvProgress.setTextSize(20);
		params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.CENTER_IN_PARENT);
		tvProgress.setLayoutParams(params);
		tvProgress.setText(StringUtils.getString(R.string.imageloadingcontent2));
		this.addView(tvProgress);

	}

	/**
	 * 设置图片
	 * 
	 * @param imageUrl
	 */
	public void setUrl(String imageUrl) {{
		if (imageUrl.startsWith("http://")){
			if (!imageUrl.contains("x-oss-process")){
				imageUrl +=  "?x-oss-process=image/format,webp";
			} else {
				imageUrl +=  "/format,webp";
			}
		}
		this.imageUrl = imageUrl;
		if (imageUrl.endsWith(".gif")) {

			if (imageUrl.startsWith("file:")){
				mGifImageView.setVisibility(VISIBLE);
				mGifImageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View view) {
						Activity activity = (Activity) mGifImageView.getTag();
						activity.finish();
					}
				});
				mImageView.setVisibility(GONE);
				tvProgress.setVisibility(GONE);
				imageLoaderClient.Glidde_loadImage(mContext,imageUrl, mGifImageView);
			} else {
				File directory = new File(Constant.gifDir);
				if (!directory.exists()) {
					directory.mkdir();//没有目录先创建目录
				}
				File file = new File(Constant.gifDir + "/" + imageUrl.hashCode() + ".gif");
				this.imageUrl = Constant.gifDir + "/" + imageUrl.hashCode() + ".gif";
				if (file.exists()) {
					mGifImageView.setVisibility(VISIBLE);
					mGifImageView.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View view) {
							Activity activity = (Activity) mGifImageView.getTag();
							activity.finish();
						}
					});
					mImageView.setVisibility(GONE);
					tvProgress.setVisibility(GONE);
					imageLoaderClient.Glidde_loadImage(mContext,"file://" + file.getPath(), mGifImageView);
				} else {
					new LoadGifTask(file).execute(imageUrl);
				}
			}
		} else {
			Glide.with(mContext).load(imageUrl).asBitmap().skipMemoryCache(true).into(new SimpleTarget<Bitmap>() {
				@Override
				public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

					try {
						mImageView.setVisibility(VISIBLE);
						mGifImageView.setVisibility(GONE);
						tvProgress.setVisibility(GONE);
						mImageView.setScaleType(ImageView.ScaleType.MATRIX);
						mImageView.setImageBitmap(resource);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				@Override
				public void onLoadFailed(Exception exception, Drawable drawable) {
					// TODO Auto-generated method stub
					super.onLoadFailed(exception, drawable);
					tvProgress.setText(StringUtils.getString(R.string.imageloadingcontent1));
				}
			});
		}


	}}

	public class LoadGifTask extends AsyncTask<String, Void, Boolean> {

		private File file;

		public LoadGifTask(File file) {
			this.file = file;
		}

		@Override
		protected Boolean doInBackground(String... arg0) {
			try {
				String url = arg0[0];
				if (!file.exists()) {
					file.createNewFile();
				}
				FileUtility.loadFileFromUrl(url, file.getPath());
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				return false;
			}

		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				mGifImageView.setVisibility(VISIBLE);
				tvProgress.setVisibility(GONE);
				mImageView.setVisibility(GONE);
				imageLoaderClient.Glidde_loadImage(mContext,"file://" + file.getPath(), mGifImageView);
			} else {
				tvProgress.setText(StringUtils.getString(R.string.imageloadingcontent1));
			}
		}
	}
}
